﻿using Microsoft.AspNetCore.Mvc;
using Seagull;
using DotNetCore.CAP;
using Microsoft.EntityFrameworkCore;
using System.Text.Json;
using Microsoft.Extensions.Options;
using Seagull.Foundation;

namespace sample1.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class HomeController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<HomeController> _logger;
        private readonly IEventBus _eventBus;
        private readonly IServiceBus _capBus;
        private readonly PostgreSQLContext _context;
        //private readonly DBContext _db_dapper;

        public HomeController(ILogger<HomeController> logger, IOptions<AppSetting> options,IEventBus eventBus, IServiceBus capPublisher, PostgreSQLContext context/*, DBContext db_dapper*/)
        {
            _logger = logger;
            _eventBus = eventBus;
            _capBus = capPublisher;
            _context = context;
            //_db_dapper = db_dapper;
        }

        [NonAction]
        [CapSubscribe("delay")]
        public void test(string p)
        {
            Console.WriteLine($@"{DateTime.Now} Subscriber invoked, Info: {p}");
        }

        [NonAction]
        [CapSubscribe("Order.Delete")]
        public void test2(string p)
        {

            Console.WriteLine($@"{DateTime.Now} Subscriber invoked, Info: {p}");
        }

        [NonAction]
        [CapSubscribe("Order.Delete", Group = "HomeController.test3")]
        public void test3(string p)
        {
            Console.WriteLine($@"{DateTime.Now} Subscriber invoked, Info: {p}");
        }


        [HttpGet]
        public async Task<string> GetAsync()
        {
            await _capBus.Delay("Order.Delete", "哈哈哈 ", new TimeSpan(0, 0, 5));
            await _capBus.Publish("Order.Delete", "哈哈哈");
            await _eventBus.Publish(new Ping());
            IServiceBus serviceBus = null;
            if (serviceBus is not null)
            {
                await serviceBus.Delay("key3", "value", TimeSpan.FromDays(5)); // 5天后执行任务。
                await serviceBus.Send("key1", "value");//通知key1的服务程序，开始处理任务，通常用于邮件通知、短信等
                await serviceBus.Publish("key2", "value");//通知所有关注key2的模块，处理相应的逻辑。
            }
            return "ok";
        }


        [HttpPost]
        public async Task<List<ModelFieldConfig>> PostAsync(ModelFieldConfig config)
        {
            var json = JsonSerializer.SerializeToDocument(new FieldConfig { Title = "测试3", Type = "Int", Name = "hhs" });
            var model = new ModelFieldConfig()
            {
                Model = "teset_xiajun",
                Config = new Dictionary<string, FieldConfig>
                {
                    ["测试列"] = new FieldConfig { Title = "测试3", Type = "Int", Name = "hhs" }
                },
                Json = json.RootElement
            };
            _context.Set<ModelFieldConfig>().Add(config);
            _context.SaveChanges();
            //获取数据
            var ent = _context.Set<ModelFieldConfig>().Where(s => s.Model == "teset_xiajun").ToList();
            return ent;
        }

        [HttpDelete]
        public async Task<object> DeleteAsync(string[] param)
        {
            //移除json字段属性 new string[] { "Age", "Name" }
            //var num = _context.Database.RemoveJsonFieldAttribute("demo.model_field_config", "Json", param, "\"Id\"=1");
            //num = _context.RemoveJsonFieldAttribute<ModelFieldConfig>(x => x.Json, param, "\"Id\"=1");
            //var arr = new string[] { "Age", "Name" };
            //var arr_json = JsonSerializer.Serialize(arr);
            //arr_json = $"{{{arr_json.TrimStart('[').TrimEnd(']')}}}";
            //num = _db_dapper.DbConnection.Execute($"UPDATE demo.\"model_field_config\" SET \"Json\"=\"Json\"::JSONB- '{arr_json}'::text[] WHERE \"Id\"=1");

            var jsonb3 = _context.Set<ModelFieldConfig>().Where(_ => _.Json.GetProperty("Name").GetString() == "客户颜色").ToList();
            return jsonb3;
        }

        [HttpPut]
        public async Task<object> UpdateAsync(Dictionary<string, object> dic)
        {
            //修改json内容
            var config = _context.Set<ModelFieldConfig>().First(x => x.Id == 2);
            config.Model = "order";
            _context.SaveChanges();


            //var dic = new Dictionary<string, object> { ["Name"] = "zhujie", ["Age"] = 99 };
            //var num = _context.Database.UpdateJsonFieldAttribute("demo.model_field_config", "Json", dic, "\"Id\"=1");
            //num = _context.UpdateJsonFieldAttribute<ModelFieldConfig>(x => x.Json, dic, "\"Id\"=1");
            //统计数据
            var jsonb5 = _context.Set<ModelFieldConfig>().Where(_ => EF.Functions.JsonContains(_.Json.GetProperty("Orders"), @"[{""ShippingAddress"": ""address1""}]")).Count();
            jsonb5 = _context.Set<ModelFieldConfig>().Sum(x => x.Json.GetProperty("Age").GetInt32());

            //获取数据
            var jsonb1 = _context.Set<ModelFieldConfig>().FirstOrDefault(s => s.Model == "Order");
            var jsonb3 = _context.Set<ModelFieldConfig>().Where(_ => _.Json.GetProperty("Name").GetString() == "客户颜色").ToList();
            var jsonb4 = _context.Set<ModelFieldConfig>().Where(_ => EF.Functions.JsonContains(_.Json.GetProperty("Orders"), @"[{""ShippingAddress"": ""address1""}]")).ToList();
            return jsonb4;
        }
    }
}